package com.ruoyi.crm.controller;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.crm.domain.dto.CrmCustomerTraceDTO;
import com.ruoyi.system.service.ISysUserService;
import com.taobao.api.ApiException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.crm.domain.CrmCustomer;
import com.ruoyi.crm.service.ICrmCustomerService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 客户列Controller
 *
 * @author yanwenliang
 * @date 2024-10-18
 */
@RestController
@RequestMapping("/crm/customer")
public class CrmCustomerController extends BaseController
{
    @Autowired
    private ICrmCustomerService crmCustomerService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询客户列列表
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:list')")
    @GetMapping("/list")
    public TableDataInfo list(CrmCustomer crmCustomer)
    {
        startPage();
        List<CrmCustomer> list = crmCustomerService.selectCrmCustomerList(crmCustomer);
        return getDataTable(list);
    }

    @GetMapping("/getList")
    public TableDataInfo getList(CrmCustomer crmCustomer){
        startPage();
        List<CrmCustomer> list = crmCustomerService.getList(crmCustomer);
        return getDataTable(list);
    }

    /**
     * 查询核心客户列列表
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:list')")
    @GetMapping("/getMyCustomerList")
    public TableDataInfo getMyCustomerList(CrmCustomer crmCustomer){
        startPage();
        return getDataTable(crmCustomerService.getMyCustomerList(crmCustomer));
    }


    /**
     * 导出客户列列表
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:export')")
    @Log(title = "客户列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CrmCustomer crmCustomer)
    {
        List<CrmCustomer> list = crmCustomerService.selectCrmCustomerList(crmCustomer);
        ExcelUtil<CrmCustomer> util = new ExcelUtil<CrmCustomer>(CrmCustomer.class);
        util.exportExcel(response, list, "客户列数据");
    }

    /**
     * 获取客户列详细信息
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:query')")
    @GetMapping(value = "/{customerId}")
    public AjaxResult getInfo(@PathVariable("customerId") String customerId)
    {
        return success(crmCustomerService.selectCrmCustomerByCustomerId(customerId));
    }

    /**
     * 新增客户列
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:add')")
    @Log(title = "客户列表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CrmCustomer crmCustomer) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, ApiException {
        return toAjax(crmCustomerService.insertCrmCustomer(crmCustomer));
    }

    /**
     * 修改客户列
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:edit')")
    @Log(title = "客户列表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CrmCustomer crmCustomer)
    {
        return toAjax(crmCustomerService.updateCrmCustomer(crmCustomer));
    }

    /**
     * 删除客户列
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:remove')")
    @Log(title = "客户列表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{customerIds}")
    public AjaxResult remove(@PathVariable String[] customerIds)
    {
        return toAjax(crmCustomerService.deleteCrmCustomerByCustomerIds(customerIds));
    }


    /**
     * 查询选择的核心客户列列表
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:list')")
    @GetMapping("/getChooseCustomerList")
    public TableDataInfo getChooseCustomerList(CrmCustomer crmCustomer){
        return getDataTable(crmCustomerService.getChooseCustomerList(crmCustomer));
    }

    /**
     * 选择核心客户列列表
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:list')")
    @PostMapping("/chooseCustomer")
    public AjaxResult chooseCustomer(@RequestBody CrmCustomer crmCustomer){
        return AjaxResult.success(crmCustomerService.chooseCustomer(crmCustomer));
    }

    /**
     * 添加跟进记录
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:list')")
    @PostMapping("/addCrmCustomerTrace")
    public AjaxResult addCrmCustomerTrace(@RequestBody CrmCustomerTraceDTO crmCustomerTraceDTO){
        return AjaxResult.success(crmCustomerService.addCrmCustomerTrace(crmCustomerTraceDTO));
    }

    /**
     * 获取全部客户的记录
     * @param crmCustomer
     * @return
     */
    @PostMapping("/getCrmCustomerAllNoPage")
    public AjaxResult getCrmCustomerAllNoPage(@RequestBody CrmCustomer crmCustomer){
        return AjaxResult.success(crmCustomerService.list(new LambdaQueryWrapper<CrmCustomer>()
                .eq(CrmCustomer::getStatus, "1")
                .orderByDesc(CrmCustomer::getCreateTime)));
    }

    /**
     * 转移客户
     * @return
     */
    @PostMapping("/transferCrmCustomer")
    public AjaxResult transferCrmCustomer(@RequestBody CrmCustomer crmCustomer){
        CrmCustomer customer = crmCustomerService.getById(crmCustomer.getCustomerId());

        if (ObjectUtils.isEmpty(customer)){
            throw new ServiceException("客户不存在，请刷新后重试！");
        }

        if (customer.getUserId().equals(crmCustomer.getUserId())){
            throw new ServiceException("新负责人不能与原负责人相同 ");
        }
        SysUser sysUser = sysUserService.selectUserById(crmCustomer.getUserId());
        return AjaxResult.success(crmCustomerService.update(new LambdaUpdateWrapper<CrmCustomer>()
                .set(CrmCustomer::getPreOwner, customer.getUserId())
                .set(CrmCustomer::getUserId, crmCustomer.getUserId())
                .set(CrmCustomer::getCreateBy, sysUser.getUserName())
                .eq(CrmCustomer::getCustomerId, crmCustomer.getCustomerId())));
    }


    /**
     * 获取客户信息
     * @param crmCustomer
     * @return
     */
    @PostMapping("getCustomerOne")
    public AjaxResult getCustomerOne(@RequestBody CrmCustomer crmCustomer){
        CrmCustomer one = crmCustomerService.getOne(new LambdaQueryWrapper<CrmCustomer>()
                .eq(CrmCustomer::getStatus, crmCustomer.getStatus())
                .eq(CrmCustomer::getUserId, SecurityUtils.getUserId()));

        return AjaxResult.success(one);
    }

    /**
     * 获取全部客户
     * @param crmCustomer
     * @return
     */
    @PostMapping("/getCustomerList")
    public AjaxResult getCustomerList(@RequestBody(required = false) CrmCustomer crmCustomer){
        return AjaxResult.success(crmCustomerService.list());
    }


}
